<?php
/***
* @version $Id: usercp_register.php 336 2007-01-23 08:12:56Z flexiondotorg $
* @copyright (c) 2006 - 2007 Flexion.Org
*            (c) 2006              Phantomk <phantomk@modmybb.com>  http://www.modmybb.com/
*            (c) 2004 - 2005 Project Minerva
*            (c) 2003 - 2004 aboyd (Tony Boyd) http://www.outshine.com/forums/
*            (c) 2003 - 2004 Kooky <kooky@altern.org> http://perso.edeign.com/kooky/
*            (c) 2001 - 2006 phpBB Group
* @license   http://opensource.org/licenses/gpl-license.php GNU Public License
***/

if ( !defined('IN_R3BORN') )
{
	die('Hacking attempt');
}

//$unhtml_specialchars_match = array('#&gt;#', '#&lt;#', '#&quot;#', '#&amp;#');
//$unhtml_specialchars_replace = array('>', '<', '"', '&');

// ---------------------------------------
// Load agreement template since user has not yet
// agreed to registration conditions
//
function show_agreement()
{
	global $userdata, $template, $lang, $root_path, $phpEx, $config;

	$template->set_filenames(array(
		'body' => 'agreement.tpl')
	);

	$temp_url = '<a href="' . append_sid("policy.$phpEx?id=%s") . '">%s</a>';
	$terms = ( get_policy(TERMS_POL_ID, 'text') ) ? sprintf($temp_url, TERMS_POL_ID, $lang['Terms_of_Use']) : '';
	$privacy = ( get_policy(PRIVACY_POL_ID, 'text') ) ? sprintf($temp_url, PRIVACY_POL_ID, $lang['Privacy_Policy']) : '';
	$legal = ( $terms xor $privacy ) ? ($terms . $privacy) : (( $terms && $privacy ) ? ($terms . ' &amp; ' . $privacy) : '');

	$template->assign_vars(array(
		'REGISTRATION' => $lang['Registration'],
		//'AGREEMENT' => $lang['Reg_agreement'],


### R3-born - ADD (Accept Terms)
#
		'AGREEMENT' => get_policy(REGISTRATION_POL_ID, 'text'),
		'SITE_RULES' => $lang['Site_Rules'],
		'TO_JOIN' => $lang['To_Join'] . ' ' . $legal . '.',

		'AGREE_CHECKBOX' => sprintf($lang['Agree_checkbox'], $config['sitename']) . ' ' . $legal . '.',
		'L_REGISTER' => $lang['Register'],
		'S_AGREE' => append_sid("register.$phpEx"),
#
### E3-born - END ADD

### R3-born - REMOVE
#
/*
		"AGREE_OVER_13" => $lang['Agree_over_13'],
		"AGREE_UNDER_13" => $lang['Agree_under_13'],
		'DO_NOT_AGREE' => $lang['Agree_not'],

		"U_AGREE" => append_sid("register.$phpEx?mode=register&amp;agreed=true"),
		"U_AGREE_UNDER13" => append_sid("register.$phpEx?mode=register&amp;agreed=true&amp;coppa=true"))
*/
#
### R3-born - END REMOVE
	));

	$template->pparse('body');

}
//
// ---------------------------------------

$error = FALSE;
$error_msg = '';
$page_title = $lang['Register'];

### R3-born - CHANGE (Accept Terms)
#
/*
if ( !isset($_POST['agreed']) && !isset($_GET['agreed']) )
{
	include($root_path . 'includes/page_header.'.$phpEx);

	show_coppa();

	include($root_path . 'includes/page_tail.'.$phpEx);
}
*/

if ( !isset($_POST['agreed']) && !isset($_POST['not_agreed']) )
{
	page_header($page_title);
	show_agreement();
	page_footer();
}
else if ( !isset($_POST['agreed']) && isset($_POST['not_agreed']) )
{
	redirect(append_sid($root_path . 'index.' . $phpEx, true));
	exit;
}
#
### R3-born - END CHANGE

//$coppa = ( empty($_POST['coppa']) && empty($_GET['coppa']) ) ? 0 : TRUE;

//
// Check and initialize some variables if needed
//
if (isset($_POST['submit']) /*|| $mode == 'register'*/ )
{
	include($root_path . 'includes/functions_validate.'.$phpEx);

	$strip_var_list = array('email' => 'email', 'email_confirm' => 'email_confirm', 'confirm_code' => 'confirm_code');

	// Strip all tags from data ... may p**s some people off, bah, strip_tags is
	// doing the job but can still break HTML output ... have no choice, have
	// to use htmlspecialchars ... be prepared to be moaned at.
	while( list($var, $param) = @each($strip_var_list) )
	{
		$$var = get_var($param, '');
	}

	$username = ( !empty($_POST['username']) ) ? r3born_clean_username($_POST['username']) : '';

	$trim_var_list = array('cur_password' => 'cur_password', 'new_password' => 'new_password', 'password_confirm' => 'password_confirm');

	while( list($var, $param) = @each($trim_var_list) )
	{
		if ( !empty($_POST[$param]) )
		{
			$$var = trim($_POST[$param]);
		}
	}

	$sid = get_var('sid', 0);
}

if ( !isset($_POST['submit']) )
{
	$username = stripslashes($username);
	$email = stripslashes($email);
	$email_confirm = stripslashes($email_confirm);
	$cur_password = htmlspecialchars(stripslashes($cur_password));
	$new_password = htmlspecialchars(stripslashes($new_password));
	$password_confirm = htmlspecialchars(stripslashes($password_confirm));
}
//}

//
// Let's make sure the user isn't logged in while registering,
// and ensure that they were trying to register a second time
// (Prevents double registrations)
//
if ( ($userdata['session_logged_in'] || $username == $userdata['username']))
{
	message_die(GENERAL_MESSAGE, $lang['Username_taken'], '', __LINE__, __FILE__);
}

//
// Did the user submit? In this case build a query to update the users profile in the DB
//
if ( isset($_POST['submit']) )
{
	$passwd_sql = '';

	if ( empty($username) || empty($new_password) || empty($password_confirm) || empty($email)|| empty($email_confirm) )
	{
		$error = TRUE;
		$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Fields_empty'];
	}
	else if ( $email != $email_confirm )
	{
		$error = TRUE;
		$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Email_mismatch'];
	}
	if ( $config['enable_confirm'])
	{
		if ( empty($_POST['confirm_id']))
		{
			$error = TRUE;
			$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Confirm_code_wrong'];
		}
		else
		{
			$confirm_id = htmlspecialchars($_POST['confirm_id']);
			if (!preg_match('/^[A-Za-z0-9]+$/', $confirm_id))
			{
				$confirm_id = '';
			}

			$sql = 'SELECT code
					FROM ' . CONFIRM_TABLE . "
					WHERE confirm_id = '$confirm_id'
					AND confirm_type = " . CAPTCHA_REGISTRATION . "
					AND session_id = '" . $userdata['session_id'] . "'";
			if (!($result = $db->sql_query($sql)))
			{
				message_die(GENERAL_ERROR, 'Could not obtain confirmation code', '', __LINE__, __FILE__, $sql);
			}

			if ($row = $db->sql_fetchrow($result))
			{
				if ($row['code'] != $_POST['confirm_code'])
				{
					$error = TRUE;
					$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Confirm_code_wrong'];
				}
				else
				{
					$sql = 'DELETE FROM ' . CONFIRM_TABLE . "
							WHERE confirm_id = '$confirm_id'
							AND session_id = '" . $userdata['session_id'] . "'";
					if (!$db->sql_query($sql))
					{
						message_die(GENERAL_ERROR, 'Could not delete confirmation code', '', __LINE__, __FILE__, $sql);
					}
				}
			}
			else
			{
				$error = TRUE;
				$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Confirm_code_wrong'];
			}
			$db->sql_freeresult($result);
		}
	}

	$passwd_sql = '';
	if ( !empty($new_password) && !empty($password_confirm) )
	{
		if ( $new_password != $password_confirm )
		{
			$error = TRUE;
			$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Password_mismatch'];
		}
		else if ( strlen($new_password) > 32 )
		{
			$error = TRUE;
			$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Password_long'];
		}
		else
		{
			if ( !$error )
			{
				$new_password = md5($new_password);
				$passwd_sql = "user_password = '$new_password', ";
			}
		}
	}
	else if ( ( empty($new_password) && !empty($password_confirm) ) || ( !empty($new_password) && empty($password_confirm) ) )
	{
		$error = TRUE;
		$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Password_mismatch'];
	}

	//
	// Do a ban check on this email address
	//
	//if ( $email != $userdata['user_email'] || $email_confirm != $userdata['user_email'] || $email != $email_confirm || $mode == 'register' )
	//{
	$result = validate_email($email);
	if ( $result['error'] )
	{
		//$email = $userdata['user_email'];
		//$email_confirm = $userdata['user_email'];
		$email = $email_confirm;

		$error = TRUE;
		$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $result['error_msg'];
	}
	else
	if ( $email != $email_confirm )
	{
		$error = TRUE;
		$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Email_mismatch'];
	}
	//}

	$username_sql = '';

	if ( empty($username) )
	{
		// Error is already triggered, since one field is empty.
		$error = TRUE;
	}
	else
	{
		$result = validate_username($username);
		if ( $result['error'] )
		{
			$error = TRUE;
			$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $result['error_msg'];
		}
	}

	if (!$error)
	{
		$username_sql = "username = '" . str_replace("\'", "''", $username) . "', ";
	}

	if ( !$error )
	{
		include_once($root_path . 'includes/functions_user.' . $phpEx);

		if ( !$insert_user_result = insert_user($username, $new_password, $email, false) )
		{
			message_die(GENERAL_ERROR, $lang['No_user_in_db'], '', __LINE__, __FILE__, $sql);
		}
	}
} // End of submit

	if ( $error )
	{
		//
		// If an error occured we need to stripslashes on returned data
		//
		$username = stripslashes($username);
		$email = stripslashes($email);
		$email_confirm = stripslashes($email_confirm);

		$cur_password = '';
		$new_password = '';
		$password_confirm = '';
	}
//}

page_header($page_title);

/*
	if ( !isset($coppa) )
	{
		$coppa = FALSE;
	}
*/

	//$s_hidden_fields = '<input type="hidden" name="mode" value="' . $mode . '" /><input type="hidden" name="agreed" value="true" /><input type="hidden" name="coppa" value="' . $coppa . '" />';
	$s_hidden_fields = '<input type="hidden" name="mode" value="' . $mode . '" /><input type="hidden" name="agreed" value="true" />';
	$s_hidden_fields .= '<input type="hidden" name="sid" value="' . $userdata['session_id'] . '" />';

### R3-born - ADD (Accept Terms)
#
	$s_hidden_fields .= '<input type="hidden" name="not_agreed" value="false" />';
#
### R3-born - END ADD

	if ( $error )
	{
		$template->set_filenames(array(
			'reg_header' => 'error_body.tpl')
		);
		$template->assign_vars(array(
			'ERROR_MESSAGE' => $error_msg)
		);
		$template->assign_var_from_handle('ERROR_BOX', 'reg_header');
	}

	$template->set_filenames(array(
		'body' => 'profile_add_body.tpl')
	);

	// Visual Confirmation
	$confirm_image = '';
	if (!empty($config['enable_confirm']))
	{
		$sql = 'SELECT session_id
			FROM ' . SESSIONS_TABLE;
		if (!($result = $db->sql_query($sql)))
		{
			message_die(GENERAL_ERROR, 'Could not select session data', '', __LINE__, __FILE__, $sql);
		}

		if ($row = $db->sql_fetchrow($result))
		{
			$confirm_sql = '';
			do
			{
				$confirm_sql .= (($confirm_sql != '') ? ', ' : '') . "'" . $row['session_id'] . "'";
			}
			while ($row = $db->sql_fetchrow($result));

			$sql = 'DELETE FROM ' .  CONFIRM_TABLE . "
				WHERE session_id NOT IN ($confirm_sql)";
			if (!$db->sql_query($sql))
			{
				message_die(GENERAL_ERROR, 'Could not delete stale confirm data', '', __LINE__, __FILE__, $sql);
			}
		}
		$db->sql_freeresult($result);

		$sql = 'SELECT COUNT(session_id) AS attempts
			FROM ' . CONFIRM_TABLE . "
			WHERE session_id = '" . $userdata['session_id'] . "'
			AND confirm_type = " . CAPTCHA_REGISTRATION;
		if (!($result = $db->sql_query($sql)))
		{
			message_die(GENERAL_ERROR, 'Could not obtain confirm code count', '', __LINE__, __FILE__, $sql);
		}

		//
		if ($row = $db->sql_fetchrow($result))
		{
			if ($row['attempts'] > 3)
			{
				message_die(GENERAL_MESSAGE, $lang['Too_many_registers']);
			}
		}
		$db->sql_freeresult($result);

		// Generate the required confirmation code
		// NB 0 (zero) could get confused with O (the letter) so we make change it
		$code = dss_rand();
		$code = substr(str_replace('0', 'Z', strtoupper(base_convert($code, 16, 35))), 2, 6);

		$confirm_id = md5(uniqid($user_ip));

		$sql = 'INSERT INTO ' . CONFIRM_TABLE . " (confirm_id, session_id, code, confirm_type)
			VALUES ('$confirm_id', '". $userdata['session_id'] . "', '$code', " . CAPTCHA_REGISTRATION . ")";
		if (!$db->sql_query($sql))
		{
			message_die(GENERAL_ERROR, 'Could not insert new confirm code information', '', __LINE__, __FILE__, $sql);
		}

		unset($code);

		$confirm_image = '<img src="' . append_sid("register.$phpEx?mode=confirm&amp;id=$confirm_id") . '" alt="" title="" />';
		$s_hidden_fields .= '<input type="hidden" name="confirm_id" value="' . $confirm_id . '" />';

		$template->assign_block_vars('switch_confirm', array());
	}


	//
	// Let's do an overall check for settings/versions which would prevent
	// us from doing file uploads....
	//
	//$form_enctype = ''; //( !@ini_get('file_uploads') || !$config['allow_avatar_upload'] ) ? '' : 'enctype="multipart/form-data"';

	$template->assign_vars(array(
		'USERNAME' => isset($username) ? $username : '',
		'CUR_PASSWORD' => isset($cur_password) ? $cur_password : '',
		'NEW_PASSWORD' => isset($new_password) ? $new_password : '',
		'PASSWORD_CONFIRM' => isset($password_confirm) ? $password_confirm : '',
		'EMAIL' => isset($email) ? $email : '',
		'CONFIRM_IMG' => $confirm_image,
		'BREADCRUMB_REG_OR_EDIT' => $lang['Register'],
		'L_CURRENT_PASSWORD' => $lang['Current_password'],
		'L_NEW_PASSWORD' => $lang['Password'],
		'L_CONFIRM_PASSWORD' => $lang['Confirm_password'],
		'L_SUBMIT' => $lang['Submit'],
		'L_RESET' => $lang['Reset'],
		'L_ITEMS_REQUIRED' => $lang['Items_required'],
		'L_REGISTRATION_INFO' => $lang['Registration_info'],
		'L_PROFILE_INFO' => $lang['Profile_info'],
		'L_PROFILE_INFO_NOTICE' => $lang['Profile_info_warn'],
		'L_EMAIL_ADDRESS' => $lang['Email_address'],
		'L_CONFIRM_EMAIL' => $lang['Email_confirm'],
		'EMAIL_CONFIRM' => $email_confirm,
		'L_CONFIRM_CODE_IMPAIRED'	=> sprintf($lang['Confirm_code_impaired'], '<a href="mailto:' . $config['board_email'] . '">', '</a>'),
		'L_CONFIRM_CODE'			=> $lang['Confirm_code'],
		'L_CONFIRM_CODE_EXPLAIN'	=> $lang['Confirm_code_explain'],
		'S_HIDDEN_FIELDS' => $s_hidden_fields,
		//'S_FORM_ENCTYPE' => $form_enctype,
		'S_PROFILE_ACTION' => append_sid("register.$phpEx"))
	);
//}

$template->pparse('body');

page_footer();

?>